<!-- src/views/admin/ProductTypesView.vue -->
<template>
  <div class="product-types-view">
    <div class="header">
      <h2>商品 <span class="highlight">标签</span></h2>
      <div class="header-actions">
        <el-button 
          type="danger" 
          size="small" 
          :disabled="selectedTags.length === 0"
          @click="deleteSelectedTags"
        >
          <i class="el-icon-delete"></i> 批量删除
        </el-button>
        <el-button type="primary" @click="showAddTagDialog" size="small">
          <i class="el-icon-plus"></i> 新增标签
        </el-button>
      </div>
    </div>
    
    <div class="types-container">
      <div class="tag-item" @click="selectTag('全部商品')">
        <div class="tag-content">
          <span class="tag-name">全部商品</span>
        </div>
      </div>
      
      <div class="tag-item" v-for="tag in tags" :key="tag.tId">
        <div class="tag-content">
          <el-checkbox 
            :value="selectedTags.includes(tag.tId)" 
            @change="(val) => handleTagSelection(val, tag.tId)"
            @click.stop
          ></el-checkbox>
          <span class="tag-name">{{ tag.tName }}</span>
          <div class="tag-actions">
            <el-button 
              type="danger" 
              size="mini" 
              @click.stop="deleteSingleTag(tag.tId)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <i class="el-icon-loading"></i> 加载中...
      </div>
      
      <!-- 空状态 -->
      <div v-if="!loading && tags.length === 0" class="empty">
        暂无商品标签数据
      </div>
    </div>
    
    <!-- 新增标签对话框 -->
    <el-dialog 
      title="新增商品标签" 
      v-model="dialogVisible" 
      width="400px"
      @close="resetForm"
    >
      <el-form :model="tagForm" :rules="tagRules" ref="tagFormRef" label-width="80px">
        <el-form-item label="标签名称" prop="tName">
          <el-input v-model="tagForm.tName" placeholder="请输入标签名称"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="addTag" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import goodApi from '@/api/controller'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ProductTypesView',
  emits: ['tag-selected'],
  setup(props, { emit }) {
    const tags = ref([])
    const dialogVisible = ref(false)
    const loading = ref(false)
    const submitLoading = ref(false)
    const selectedTags = ref([]) // 选中的标签ID数组
    
    // 表单数据
    const tagForm = reactive({
      tName: ''
    })
    
    // 表单验证规则
    const tagRules = {
      tName: [
        { required: true, message: '请输入标签名称', trigger: 'blur' }
      ]
    }
    
    const tagFormRef = ref(null)
    
    // 获取商品标签列表
    const fetchTags = async () => {
      loading.value = true
      try {
        const response = await goodApi.getType()
        if (response && response.code === 200) {
          tags.value = response.data || []
        } else {
          ElMessage.error('获取商品标签失败: ' + (response?.message || '未知错误'))
        }
      } catch (error) {
        console.error('获取商品标签失败:', error)
        ElMessage.error('获取商品标签失败: ' + error.message)
      } finally {
        loading.value = false
      }
    }
    
    // 选择标签
    const selectTag = (tagName) => {
      emit('tag-selected', tagName)
    }
    
    // 处理标签选择
    const handleTagSelection = (checked, tagId) => {
      if (checked) {
        selectedTags.value.push(tagId)
      } else {
        selectedTags.value = selectedTags.value.filter(id => id !== tagId)
      }
    }
    
    // 显示新增标签对话框
    const showAddTagDialog = () => {
      dialogVisible.value = true
    }
    
    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false
      resetForm()
    }
    
    // 新增标签
    const addTag = () => {
      tagFormRef.value.validate(async (valid) => {
        if (valid) {
          submitLoading.value = true
          try {
            // 调用新增标签接口
            const tagData = {
              tName: tagForm.tName
            }
            
            const response = await goodApi.addType(tagData)
            if (response && response.code === 200) {
              ElMessage.success('新增标签成功')
              closeDialog() // 关闭对话框
              await fetchTags() // 重新获取列表
            } else {
              ElMessage.error('新增标签失败: ' + (response?.message || '未知错误'))
            }
          } catch (error) {
            console.error('新增标签失败:', error)
            ElMessage.error('新增标签失败: ' + error.message)
          } finally {
            submitLoading.value = false
          }
        }
      })
    }
    
    // 删除单个标签
    const deleteSingleTag = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个商品标签吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 调用删除标签接口，传入单个ID
        const response = await goodApi.deleteTypeById(id)
        if (response && response.code === 200) {
          ElMessage.success('删除标签成功')
          // 从选中列表中移除（如果已被选中）
          selectedTags.value = selectedTags.value.filter(tagId => tagId !== id)
          await fetchTags() // 重新获取列表
        } else if (response && response.status === 404) {
          ElMessage.error('删除标签失败: 后端接口未实现')
        } else {
          ElMessage.error('删除标签失败: ' + (response?.message || '未知错误'))
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败: ' + (error.message || '操作已取消'))
        }
      }
    }
    
    // 批量删除标签
    const deleteSelectedTags = async () => {
      if (selectedTags.value.length === 0) {
        ElMessage.warning('请先选择要删除的标签')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除选中的${selectedTags.value.length}个商品标签吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 调用删除标签接口，传入选中ID数组
        const response = await goodApi.deleteTypeById(selectedTags.value)
        if (response && response.code === 200) {
          ElMessage.success('批量删除标签成功')
          selectedTags.value = [] // 清空选中项
          await fetchTags() // 重新获取列表
        } else if (response && response.status === 404) {
          ElMessage.error('批量删除标签失败: 后端接口未实现')
        } else {
          ElMessage.error('批量删除标签失败: ' + (response?.message || '未知错误'))
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败: ' + (error.message || '操作已取消'))
        }
      }
    }
    
    // 重置表单
    const resetForm = () => {
      tagForm.tName = ''
      if (tagFormRef.value) {
        tagFormRef.value.resetFields()
      }
    }
    
    onMounted(() => {
      fetchTags()
    })
    
    return {
      tags,
      dialogVisible,
      loading,
      submitLoading,
      selectedTags,
      tagForm,
      tagRules,
      tagFormRef,
      selectTag,
      handleTagSelection,
      showAddTagDialog,
      closeDialog,
      addTag,
      deleteSingleTag,
      deleteSelectedTags,
      resetForm
    }
  }
}
</script>

<style scoped>
.product-types-view {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.highlight {
  color: #409eff;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.types-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tag-item {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
}

.tag-item:hover {
  background-color: #ecf5ff;
}

.tag-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.tag-content .el-checkbox {
  margin-right: 10px;
}

.tag-name {
  font-size: 14px;
  color: #606266;
  flex: 1;
}

.tag-actions {
  display: flex;
  gap: 8px;
}

.loading, .empty {
  text-align: center;
  padding: 20px;
  color: #999;
}

.loading i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-button {
  font-size: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #eee;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    align-self: flex-end;
  }
  
  .product-types-view {
    padding: 15px;
  }
  
  .tag-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .tag-actions {
    align-self: flex-end;
  }
}
</style>